package cc.shacocloud.luanniao.web.model.convert

import cc.shacocloud.luanniao.core.model.po.KnowledgeBasePo
import cc.shacocloud.luanniao.core.service.UserService
import cc.shacocloud.luanniao.core.utils.ApplicationContextHolder
import cc.shacocloud.luanniao.web.model.dto.output.KnowledgeBaseOutput
import cc.shacocloud.luanniao.web.model.dto.output.UserOutput
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl

private val userService: UserService by lazy {
    ApplicationContextHolder.getInstance().getBean(UserService::class.java)
}

suspend fun KnowledgeBasePo.toOutput(): KnowledgeBaseOutput {
    val creator = userService.findById(creatorId)?.toOutput()
    return KnowledgeBaseOutput(
        id = requireNotNull(id),
        createTime = requireNotNull(createTime),
        lastUpdateTime = requireNotNull(lastUpdateTime),
        name = name,
        type = type,
        avatar = avatar,
        description = description,
        parentId = parentId,
        creator = creator,
        aiModelId = aiModelId,
        namespaceId = namespaceId
    )
}

suspend fun Page<KnowledgeBasePo>.toOutput(): Page<KnowledgeBaseOutput> {
    val userMap = mutableMapOf<Long, UserOutput>()

    val contents = content.map {
        // 创建者
        val creator = userMap[it.creatorId] ?: (
            userService.findById(it.creatorId)?.toOutput()
                ?.also { user ->
                    userMap[it.creatorId] = user
                }
            )

        KnowledgeBaseOutput(
            id = requireNotNull(it.id),
            createTime = requireNotNull(it.createTime),
            lastUpdateTime = requireNotNull(it.lastUpdateTime),
            name = it.name,
            type = it.type,
            avatar = it.avatar,
            description = it.description,
            parentId = it.parentId,
            creator = creator,
            aiModelId = it.aiModelId,
            namespaceId = it.namespaceId
        )
    }

    return PageImpl(contents, pageable, totalElements);
}